<?
/**
 *票务通订单类.
 *主要用于票票付通平台会员的订单统计，查询操作
 */
class ProOrder
{
    /**
     *票付通内部接口
     *@var object
     */
    public $s;

    /**
     *登陆会员ID
     *@var int
     */
    public $did;

    /**
     *总订单数
     *@var int
     */
    //public $totalOrders;

    /**
     *订单查询参数,键值数组
     *@var array
     */
    public $params;

    /**
     *订单查询初始参数，键值数组
     *@var array
     */
    private $initParam;
    private $products = array();

    /*
     * 缓存票类成本价
     * */
    public $chenbeng=array();
    /**
     *构造函数.
     *会初始化初始查询参数 initParam（默认权限全开）
     *@param class $s 票付通内部接口
     *@param class $did 会员表ID
     */
    public function __construct($did, $s)
    {
        $this->s = $s;
        $this->did = $did;
        $this->initParam = $this->params = array(
            "status" => "",
            "pays" => "",
            "orderby" => 1,
            "sort" => 1,
            "rstart" => 0,
            "n" => 999999,//销售报表默认使用该参数。
            "c" => 0,
            "stype" => 0,
            "payinfo" => "",
            "pmode" => 0,
            "remotenum" => "0",
            "origin" => 0,
            "p_type" => "",
            "order_confirm" => "",
            "aid" => "",
            "concat" => 0,
            "ifpack" => 0,
            "ifTrans"=> 0,//0查看自供应订单，1查看转分销订单
            "contacttel"=>"",
            "area"=>"",
        );
    }

    /**
     *修改订单查询初始参数函数.
     *有查询权限的限制，必须调用该函数增加限制条件
     *@param string $key 对应查询接口参数名
     *@param string $value 对应$key参数的值
     *@return void
     */
    public function setInitParam($key, $value)
    {
        $this->initParam[$key] = $value;
    }

    /**
     *还原订单查询初始函数.
     *用于增加查询条件之后的参数还原
     *@return void
     */
    public function init()
    {
        $this->params = $this->initParam;
    }

    /**
     *订单查询参数处理.
     *接收来自页面$_GET传递过来的查询参数请求处理，将查询条件添加到params里，会更改params的值
     *值涉及时间，排序，支付方式等不涉及用户查询权限的值，传入是mid和aid时需判定是否该初始限定已存在
     */
    public function handleRequest()
    {

        $tjs = array(
            0 => "ordernum",
            1 => "ltitle",
            2 => "oname",
            3 => "otel",
            6 => "remotenum");
        $btimes = array(
            1 => "btime1",
            2 => "btime2",
            3 => "btime3");
        $etimes = array(
            1 => "etime1",
            2 => "etime2",
            3 => "etime3");

        $text = trim($_GET['txt']);
        $text = strip_tags ( $text );
        $text = htmlspecialchars ( $text, ENT_QUOTES,"UTF-8");

        $len = mb_strlen($text, 'utf-8');
        if(is_numeric($text) && $len==11 && abs($_GET['tjs']) != 6 || $text=='12301') {

            $this->params['otel'] = $text;
        }elseif(is_numeric($text) && $len<11 && abs($_GET['tjs']) == 7) {
            //已卖出产品、已买到产品 查询条件 增加 凭证码查询（有权限的企业才可看到此项）
            $vcode_landname = htmlspecialchars(strip_tags(urldecode(trim($_GET['vcode_landname']))));
            $sel_salerID = "SELECT salerid from uu_land where title='$vcode_landname' limit 1";
            $GLOBALS['le']->query($sel_salerID);
            $GLOBALS['le']->fetch_assoc();
            $salarID = $GLOBALS['le']->f('salerid');
            $this->params['ordernum']  = $this->s->Code_Verify_Order($salarID,$text,$_SESSION['sid']);
            if($_GET['cs'])
                echo $this->params['ordernum'];
        }elseif(is_numeric($text) && $len<11 && abs($_GET['tjs']) != 6) {
            $this->params['ordernum'] = $text;
        }elseif(!is_numeric($text) && $len<5 && abs($_GET['tjs']) == 2) {
            //取票人
            $this->params['oname'] = $text;
        }elseif($_GET['tjs']==6){// 远端订单号
            $this->params['remotenum'] = $text;
        }else{
            if(abs($_GET['tjs']) == 4){
                if (!$this->params['mid']) { //分销商初始条件不存在
                    $str = "SELECT id from pft_member where dname='$text'";
                    //$str = "SELECT id FROM pft_member WHERE dname LIKE '%$text%'";
                    $GLOBALS['le']->query($str);
                    $mids = array();
                    while ($row = $GLOBALS['le']->fetch_assoc()) {
                        $mids[] = $row['id'];
                        if (count($mids) > 9)
                            break;
                    }
                    if (!$mids) $this->params['mid'] = -1;
                    else {
                        $mids = implode("|", $mids);
                        $this->params['mid'] = $mids;
                    }
                    $this->params['aid'] = $this->did;
                    //如果是amin账号
                    if($_SESSION['sid']==1){
                        $this->params['aid']='1';
                        $this->params['mid']='1';
                    }
                    //如果是集团供应商保持不变
                    if($_SESSION['dtype']==7){
                        $this->params['aid'] =$tmpAid;
                    }

                }
            }elseif (abs($_GET['tjs'] == 5)){ //搜索供应商
                if (!$this->params['aid']) { //供应商初始条件不存在
                    $str = "select * from pft_member where dname='$text'";
                    //$str = "select * from pft_member where dname like '%$text%'";
                    $GLOBALS['le']->query($str);
                    $aids = array();
                    // $arr = array();
                    while ($row = $GLOBALS['le']->fetch_assoc()) {
                        // print_r($row);
                        $arr[]= $row;
                        $aids[] = $row['id'];
                        if (count($aids) > 9)
                            break; //搜出的供应商太多只搜出前9个
                    }
                    // print_r($arr);
                    if (!$aids) $this->params['aid'] = -1;
                    else{
                        $aids = implode("|", $aids);
                        $this->params['aid'] = $aids;
                    }
                    $this->params['mid'] = $this->did;
                }
                // exit;
            }else{
                $this->params[$tjs[abs($_GET['tjs'])]] = mysql_real_escape_string($text);
            }
        }

        if(isset($_GET['payinfo'])){ //支付方式
            $this->params['payinfo'] = implode("|", $_GET['payinfo']);
        }

        // 默认查询当天
        if(empty($_GET['begintime'])) $_GET['begintime'] = date('Y-m-d');
        if(empty($_GET['endtime'])) $_GET['endtime'] = date('Y-m-d');
        if(empty($_GET['xtimes'])) $_GET['xtimes'] = 1;

        if(($_GET['begintime'] || $_GET['endtime']) && !$_GET['txt']){ //查询时间段
            $this->params[$btimes[abs($_GET['times'])]] = $_GET['begintime'];
            $this->params[$etimes[abs($_GET['times'])]] = $_GET['endtime'];
        }

        //按时间查询订单
        if(isset($_GET['begintime']) && $_GET['begintime']){
            if ($this->params['ordernum']) {
                $_GET['begintime'] = date('Y-m-d');
                $_GET['endtime'] = date('Y-m-d');
            }
            $etime = $_GET['endtime'] ? $_GET['endtime']:date("Y-m-d");
            if(strlen($etime)==10) $etime.=' 23:59:59';
            if($_GET['xtimes']==1) {
                $this->params['btime1'] = $_GET['begintime'];
                $this->params['etime1'] = $etime;
            } elseif($_GET['xtimes'] == 2) {
                $this->params['btime2'] = $_GET['begintime'];
                $this->params['etime2'] = $etime;
            } else if($_GET['xtimes'] == 3) {
                $this->params['btime3'] = $_GET['begintime'];
                $this->params['etime3'] = $etime;
            }
        }


        if(isset($_GET['orderby'])){ //排序
            $this->params['orderby'] = $_GET['orderby'];
        }
        if(isset($_GET['sort'])){ //升降序
            $this->params['sort'] = $_GET['sort'];
        }
        if(isset($_GET['status']) && $_GET['status'] !== ""){ //订单状态
            $this->params['status'] = $_GET['status'];
            if(is_array($_GET['status'])){
                foreach($_GET['status'] as $v){
                    $r_status .= $v.'|';
                }
                $this->params['status'] = substr($r_status,0,-1);
            }
            if($this->params['status']=='Array')
                $this->params['status'] ='';
        }
        if(!$_GET['status'])
            $this->params['status'] ='';
        if(trim($_GET['ordernum'])){ //订单号
            $this->params['ordernum'] = trim($_GET['ordernum']);
        }
        if(is_numeric($_GET['pays'])){ // 按支付状态
            $this->params['pays'] = $_GET['pays'];
        }
        // 订单状态（多选）
        // if (isset($_GET['status']) && is_array($_GET['status'])){
        // $this->params['status'] = implode("|", $_GET['status']);
        // }

        //查询订单时从0开始
        if($this->params['ordernum']){
            $this->params['rstart'] = 0;
        }

        if($_GET['supplier']) $this->params['aid'] = $_GET['supplier'] + 0;// 供应商
        if($_GET['distributor']) $this->params['mid'] = $_GET['distributor'];// 分销商

        // 区域与联系人
        if($_GET['area']) $this->params['area'] = $_GET['area'];
        if($_SESSION['sdtype']==5) $this->params['contacttel'] = $_SESSION['account'];
        if($_GET['product']){
            $sql="select id as lid from uu_land where title='".$_GET['product']."' limit 1";
            $GLOBALS['le']->query($sql);
            $GLOBALS['le']->fetch_assoc();
            $lid=$GLOBALS['le']->f('lid');
            $this->params['lid']=$lid;//景区ID
        }
    }

    /**
     *返回订单总数
     *请确保调用过查询接口，否则该值为空
     *@return int
     */
    public function orderlistTotal()
    {
        return $this->totalOrders();
    }

    /**
     *订单查询分页函数.
     *联票订单按一条汇总显示
     *@param int currentPage 当前页
     *@param int pageSize  每页显示记录数
     *@return array
     */
    public function orderlist($currentPage = 1, $pageSize = 15)
    {

        $this->init();
        $this->handleRequest();
        $this->params['rstart'] = ($currentPage - 1) * $pageSize;
        $this->params['n'] = $pageSize;
        //员工查询需找到公司id
        if($_SESSION['dtype']==6 && isset($_SESSION['sid']))
            $this->params['mid'] = $_SESSION['sid'];
        $simplexml = $this->ordersSimpleXml();
        $result = array();
        $other = array();
        foreach ($simplexml->Rec as $row) {

            //处理转供应产品价格
            $row = $this->secondProOrderHandle($row);

            if ($this->params['ordernum']) { //直接查订单号，
                if ($this->params['ordernum'] != $row->UUordernum){
                    $other = $row;
                    continue;
                }
                $array= array(0 => $row);
                $result[] = OrderRecord::_format($array,$other);
            } else {
                if ($row->UUconcat_id == "main" || $row->UUifpack == 1) {
                    $or = new OrderRecord((string )$row->UUordernum, $this->s);
                    $result[] = $or->info();
                } else {

                    $array = array(0 => $row);
                    $result[] = OrderRecord::format($array);
                }
            }

        }
        return $result;
    }

    /**
     *订单查询分页函数.
     *联票订单按一条汇总显示
     *@param int currentPage 当前页
     *@param int pageSize  每页显示记录数
     *@return array
     *说明：为解决查询从订单一并列出主订单稍作改写；
     */
    public function _orderlist($currentPage = 1, $pageSize = 15, $concat=0)
    {

        $this->init();
        $this->handleRequest();
        $this->params['rstart'] = ($currentPage - 1) * $pageSize;
        $this->params['n'] = $pageSize;
        $this->params['concat']=$concat;
        $simplexml = $this->ordersSimpleXml();
        $this_ordernum = $this->params['ordernum'];
        if(count($simplexml)==1){// 一张表示按订单号搜索
            if($simplexml->Rec->UUconcat_id!=0){ // 联票订单获取所有关联
                $this->params['concat']=1;
                $this->params['ordernum'] = (string)$simplexml->Rec->UUconcat_id;
                $simplexml = $this->ordersSimpleXml();
            }
        }
        $reset = $simplexml->Rec[0];
        $end = $simplexml->Rec[count($simplexml)-1];

        if((int)$reset->UUconcat_id!=0){ // 头部的订单 如果是联票是话 可能没有把全部的联票都取到
            $this->params['concat']=1;
            $this->params['ordernum'] = (int)$reset->UUconcat_id;
            $simplexml_reset = $this->ordersSimpleXml();
        }


        if((int)$end->UUconcat_id!=0){ //同上 尾部的订单 如果是联票是话 可能没有把全部的联票都取到
            $this->params['concat']=1;
            $this->params['ordernum'] = (int)$end->UUconcat_id;
            $simplexml_end = $this->ordersSimpleXml();
        }
        //参数还原
        $this->params['concat']='';
        $this->params['ordernum']=$this_ordernum;


        $result = array();
        $ordernum='';
        if(count($simplexml->Rec)){
            foreach ($simplexml->Rec as $row) {
                //处理转供应产品价格
                if($ordernum[(int)$row->UUordernum]) continue;
                $ordernum[(int)$row->UUordernum]=1;
                $row = $this->secondProOrderHandle($row);
                //处理每级分销的支付方式
                $row = $this->pmode($row);
                $array = array(0 => $row);
                $result[] = OrderRecord::format($array);
            }
        }
        if(count($simplexml_reset->Rec)){
            foreach ($simplexml_reset->Rec as $row) {
                //处理转供应产品价格
                if($ordernum[(int)$row->UUordernum]) continue;
                $ordernum[(int)$row->UUordernum]=1;
                $row = $this->secondProOrderHandle($row);
                //处理每级分销的支付方式
                $row = $this->pmode($row);
                $array = array(0 => $row);
                $result[] = OrderRecord::format($array);
            }
        }
        if(count($simplexml_end->Rec)){
            foreach ($simplexml_end->Rec as $row) {
                //处理转供应产品价格
                if($ordernum[(int)$row->UUordernum]) continue;
                $ordernum[(int)$row->UUordernum]=1;
                $row = $this->secondProOrderHandle($row);
                //处理每级分销的支付方式
                $row = $this->pmode($row);
                $array = array(0 => $row);
                $result[] = OrderRecord::format($array);
            }
        }

        return $result;
    }

    /**
     *转供应产品订单记录处理函数
     *转供应产品价格处理，使多级价格能正确显示
     *@param int currentPage 当前页
     *@param int pageSize  每页显示记录数
     *@return array
     */
    public function secondProOrderHandle($row)
    {
        if((int)$row->UUsellid==0){
            $row->UUsellid = $row->UUaid;
        }
        if((int)$row->UUbuyid==0){
            $row->UUbuyid = $row->UUmid;
        }

        if ((string)$row->UUaids) { //是多级供应产品
            $UUtprices = array();
            $UUaids = explode(",", (string)$row->UUaids);
            $UUaids_price = explode(",", (string)$row->UUaids_price);
            if($_SESSION['dtype']==2 || $_SESSION['dtype']==3)
                $this->params['aid']=$UUaids[0];
            /*转供应商家查已卖出产品*/
            if ($this->params['aid'] || $_SESSION['sid']==1/*管理员都按卖出订单来算*/) {
                //转供应价格 如UUaids:81,94 UUaids_price:4. 就是81供应价是4，94分销价是4
                for ($i = 0; $i < count($UUaids) - 1; $i++) {
                    $UUtprices[$UUaids[$i]] = $UUaids_price[$i];
                }

                $UUtprices[(string)$row->UUaid]=(string)$row->UUtprice;
                $aids = ($_SESSION['sid']==1) ? array((int)$row->UUsellid) :array($this->params['aid']);

                /*从最初供应商逐级查询，优先显示多级价*/
                foreach($UUtprices as $aid=>$tprice){
                    if(in_array($aid,$aids)){
                        $row->SecondHand = 1;
                        $pos = array_search($aid,$UUaids);
                        $row->UUorigin_mid = $row->UUmid;
                        // $row->UUmid = $UUaids[$pos + 1];
                        $row->UUtprice = $tprice;
                        if($_SERVER['SCRIPT_URL']=='/orderReport.html'){
                            if ($pos > 0) {
                                $uu_price = explode(',', $row->UUaids_price);
                                $chenbeng = $uu_price[$pos - 1];
                            } else {
                                //是转供应产品，但是查看的是最初的供应商利润
                                $chenbeng = $row->UUaprice;
                            }
                            $row->UUlirun = intval($tprice - $chenbeng);
                        }
                    }
                }
            }
            if ($this->params['mid']) {
                $UUmids=$UUaids;
                $UUmids[]=(string)$row->UUmid;
                $UUtprice[(string)$row->UUmid]=(string)$row->UUtprice;
                for ($i = 1; $i < count($UUaids); $i++) {
                    $UUtprices[$UUaids[$i]] = $UUaids_price[$i - 1];
                }
                $mids = explode("|", $this->params['mid']);
                /*从最初分销商逐级查询，优先显示多级价*/
                foreach($UUtprices as $mid=>$tprice){
                    if(in_array($mid,$mids)){
                        $row->SecondHand = 1;
                        $pos = array_search($mid,$UUmids);
                        $row->UUaid = $UUmids[$pos - 1];
                        $row->UUtprice =$tprice;
                        $row->UUtotalmoney = $row->UUtprice * $row->UUtnum;
                    }
                }
            }
        }elseif($_SESSION['sid']!=1){
            $row->UUlirun =  (int)$row->UUtprice - (int)$row->UUaprice;
        }
        return $row;
    }

    /**
     *订单当日汇总统计.
     *显示当天的订单汇总信息,在首页店铺提醒显示
     *@return array
     */
    public function dayOrdersCount()
    {
        $sum=array(0,0,0);
        $btime1 = date("Y-m-d 00:00:00");
        $etime1 = date("Y-m-d 23:59:59");
        $result=$this->orderSum($btime1, $etime1);
        foreach($result as $lid=>$row){
            $sum[0]+=$row['order'];
            $sum[1]+=$row['tnum'];
            $sum[2]+=$row['money'];
        }
        return $sum;
    }
    /**
     *指定日期的订单汇总统计.
     *显示当天的订单汇总信息,在首页店铺提醒显示
     *@return array
     */
    public function _dateOrdersCount($btime='',$etime=''){
        if(!$btime)
            $btime = date('Y-m-d');
        if(!$etime)
            $etime = date('Y-m-d');
        $sum=array(0,0,0);
        $btime1 = $btime.' 00:00:00';
        $etime1 = $etime.' 23:59:59';
        $result=$this->orderSum($btime1, $etime1);
        foreach($result as $lid=>$row){
            $sum[0]+=$row['order'];
            $sum[1]+=$row['tnum'];
            $sum[2]+=$row['money'];
        }
        return $sum;
    }
    /**
     *1个月内订单销售统计函数.
     *显示1个月内的订单信息
     *@return array
     */
    public function monthOrders()
    {

        $btime1 = date("Y-m-d 00:00:00", strtotime('-1 month',$_SERVER['REQUEST_TIME'] ));
        $etime1 = date("Y-m-d 23:59:59");
        return $this->orderSum($btime1, $etime1);
    }
    /**
     *7日订单销售统计函数.
     *显示7天的订单报表汇总信息
     *@return array
     */
    public function weekOrders()
    {

        $btime1 = date("Y-m-d 00:00:00", strtotime('-7 days',$_SERVER['REQUEST_TIME'] ));
        $etime1 = date("Y-m-d 23:59:59");
        return $this->orderSum($btime1, $etime1);
    }


    /**
     *当天订单销售统计函数.
     *显示当天的订单报表汇总信息
     *@return array
     */
    public function dayOrders()
    {
        $btime1 = date("Y-m-d 00:00:00");
        $etime1 = date("Y-m-d 23:59:59");
        return $this->orderSum($btime1, $etime1);
    }

    /**
     * 订单销售统计函数.用于报表查询统计
     *
     * @param $begintime 开始时间
     * @param $endtime 结束时间
     * @param string $by 统计方式:lid按景区,tid按门票,mid按分销商
     * @param array $option 查询参数
     * @param int $timeType 时间类型1下单时间2使用时间3游玩时间(cgp, 2014年1月24日 13:52:18)
     * @param int $fid   分销商ID
     * @return array
     */
    public function orderSum($begintime, $endtime, $by = "lid",
                             $option = array(), $timeType=1, $fid=0)
    {
        $this->init();
        $this->handleRequest();
        $btime1 = $begintime;
        $etime1 = $endtime;
        $this->params['concat'] = 0;
        $this->params['sort'] ='';
        $this->params['orderby'] = '';
        if($fid>0 && $_SESSION['dtype'] !=7) {
            $this->params['mid'] = $fid;
        }
        if($fid>0 && $_SESSION['dtype'] ==7) {
            $this->params['aid'] = $fid;
        }
        switch($timeType) {
            case 2:
                $this->params['btime2'] = $btime1;
                $this->params['etime2'] = $etime1;
                break;
            case 3:
                $this->params['btime3'] = $btime1;
                $this->params['etime3'] = $etime1;
                break;
            default:
                $this->params['btime1'] = $btime1;
                $this->params['etime1'] = $etime1;
                break;
        }
        foreach ($option as $key => $value) {
            $this->params[$key] = $value;
        }
        $simplexml = $this->ordersSimpleXml();
        $result = array();
        $UUby = "UU" . $by;
        foreach ($simplexml->Rec as $row) {
            if ($row->UUpaystatus != 1)
                continue; //未支付订单不统计
            // print_r($row);
            $row = $this->secondProOrderHandle($row); //转供应产品价格处理
            if ($by == "lid") {
                $result[(string )$row->{$UUby}]['title'] = (string )$row->UUltitle;
            } elseif ($by == "tid") {
                $result[(string )$row->{$UUby}]['title'] = (string )$row->UUltitle . (string )$row->
                        UUttitle;
            } else {
                $result[(string )$row->{$UUby}]['title'] = (string )$row->UUdname;
            }
            $result[(string )$row->{$UUby}]['order']++;
            $result[(string )$row->{$UUby}]['tnum'] += $row->UUtnum;
            $result[(string )$row->{$UUby}]['money'] += (float)$row->UUtnum*(float)$row->UUtprice;
            if ((string )$row->UUpmode == 0)
                $result[(string )$row->{$UUby}]['pmode0'] += (float)$row->UUtnum * (float)$row->
                        UUtprice;
            if ((string )$row->UUpmode == 1)
                $result[(string )$row->{$UUby}]['pmode1'] += (float)$row->UUtnum * (float)$row->
                        UUtprice;
            if ((string )$row->UUpmode == 2)
                $result[(string )$row->{$UUby}]['pmode2'] += (float)$row->UUtnum * (float)$row->
                        UUtprice;
            if ((string )$row->UUpmode == 3)
                $result[(string )$row->{$UUby}]['pmode3'] += (float)$row->UUtnum * (float)$row->
                        UUtprice;
        }
        return $result;
    }


    /**
     * 订单销售统计函数.用于报表查询统计
     *
     * @param $begintime 开始时间
     * @param $endtime 结束时间
     * @param string $by 统计方式:lid按景区,tid按门票,mid按分销商
     * @param array $option 查询参数
     * @param int $timeType 时间类型1下单时间2使用时间3游玩时间(cgp, 2014年1月24日 13:52:18)
     * @param int $fid   分销商ID
     * @return array    上面的改写，统计方式不一样
     */
    public function _orderSum_bk($begintime, $endtime, $by = "lid", $option = array(), $timeType=1, $fid=0,$aid=0)
    {
        $this->init();
        $btime1 = $begintime;
        $etime1 = $endtime;
        $this->params['concat'] = 0;
        $this->params['sort'] ='';
        $this->params['orderby'] = '';
        if($fid>0) $this->params['mid'] = $fid;
        if($aid>0) $this->params['aid'] = $aid;
        switch($timeType) {
            case 2:
                $this->params['btime2'] = $btime1;
                $this->params['etime2'] = $etime1;
                break;
            case 3:
                $this->params['btime3'] = $btime1;
                $this->params['etime3'] = $etime1;
                break;
            default:
                $this->params['btime1'] = $btime1;
                $this->params['etime1'] = $etime1;
                break;
        }
        foreach ($option as $key => $value) {
            $this->params[$key] = $value;
        }

        $simplexml = $this->ordersSimpleXml();
        $result = array();
        $UUby = "UU$by";
        $products = array();
        foreach ($simplexml->Rec as $row) {

            // 转供应产品价格处理
            $row = $this->secondProOrderHandle($row);
            // 获取这些订单销售的产品列表
            if(!in_array((string)$row->UUltitle,$products))	$products[(string)$row->UUlid]=(string)$row->UUltitle;

            // 根据分销商统计
            $arrId = ($by!='lid' && $by!='tid') ? (string)$row->UUbuyid:(string )$row->{$UUby};

            // 根据景区或门票统计
            if($by == "lid") $result[$arrId]['title'] = (string )$row->UUltitle;
            if($by == "tid") $result[$arrId]['title'] = (string )$row->UUltitle.(string )$row->UUttitle;

            //已支付的订单才统计
            if($row->UUpaystatus==1){
                $result[$arrId]['order']++;
                $result[$arrId]['tnum'] += $row->UUtnum;
                $result[$arrId]['money'] += (float)$row->UUtnum*(float)$row->UUtprice;
                if((string )$row->UUpmode == 0)// 余额
                    $result[$arrId]['pmode0'] += (float)$row->UUtnum * (float)$row->UUtprice;
                if((string )$row->UUpmode == 1)// 支付宝
                    $result[$arrId]['pmode1'] += (float)$row->UUtnum * (float)$row->UUtprice;
                if((string )$row->UUpmode == 2)// 授信支付
                    $result[$arrId]['pmode2'] += (float)$row->UUtnum * (float)$row->UUtprice;
                if((string )$row->UUpmode == 3)// 自销
                    $result[$arrId]['pmode3'] += (float)$row->UUtnum * (float)$row->UUtprice;
            }
            // 现场支付   必须是已使用
            if((string)$row->UUpaystatus==0 && (string)$row->UUstatus==1){
                $result[$arrId]['pmode4'] +=(float)$row->UUtnum * (float)$row->UUtprice;
                $result[$arrId]['order']++;
                $result[$arrId]['tnum'] += $row->UUtnum;
                $result[$arrId]['money'] += (float)$row->UUtnum*(float)$row->UUtprice;
            }
        }

        $this->products = $products; // 存储订单的产品，供使用
        return $result;
    }
    // 获取订单的产品列表
    public function getOrderProducts(){
        return $this->products;
    }

    public function _orderSum($btime1, $etime1, $by = "lid",
                              $option = array(), $timeType=1, $fid=0,$aid=0,$fenid='')
    {
        $this->init();
        $this->handleRequest();
        $this->params['btime2'] = $this->params['etime2'] =$this->params['btime1'] =$this->params['etime1'] =$this->params['btime3'] =$this->params['etime3'] ='';
        $this->params['concat'] = 0;
        $this->params['sort'] ='';
        $this->params['orderby'] = '';
        if($fid>0) $this->params['mid'] = $fid;
        if($fid=='1sanke') $this->params['mid'] = '';
        if($aid>0) $this->params['aid'] = $aid;
        switch($timeType) {
            case 2:
                $this->params['btime2'] = $btime1;
                $this->params['etime2'] = $etime1;
                break;
            case 3:
                $this->params['btime3'] = $btime1;
                $this->params['etime3'] = $etime1;
                break;
            default:
                $this->params['btime1'] = $btime1;
                $this->params['etime1'] = $etime1;
                break;
        }
        foreach ($option as $key => $value) {
            $this->params[$key] = $value;
        }

        // 查询已使用时被终端修改也显示
        if(strpos('a'.$this->params['status'],'1') && !strpos('a'.$this->params['status'],'5')){
            $this->params['status']=$this->params['status'].'|5';
        }

        if ($_GET['order_type'] == 3 && !$this->params['status']) {
        	if ($this->params['status']) {
        		$status_arr = explode('|', $this->params['status']);
			    if (in_array('3', $status_arr)) {
			        unset($status_arr[array_search('3', $status_arr)]);
			    }
			    if (in_array('6', $status_arr)) {
			        unset($status_arr[array_search('6', $status_arr)]);
			    }
			    if (in_array('5', $status_arr)) {
			        unset($status_arr[array_search('5', $status_arr)]);
			    }
			    $this->params['status'] = implode('|', $status_arr);
        	} else {
                $this->params['status'] = '1|3|5|6|7';
        	}
        }

        $simplexml = $this->ordersSimpleXml();

        if($_GET['order_type']=='2'){//查退票和已取消的订单
            $result = $this->cancel($simplexml,$by);
            
            return $result;
        }
        $result = array();
        $UUby = "UU$by";
        $products = array();
        //新加入了查找子票的母套票卖给了谁的数量统计
        //by KaZeline zax
        //2015-1-5
        if($fenid!=''){
            foreach($simplexml->Rec as $row){
                if((int)$row -> UUpack_order == 0 ) continue;
                $x = simplexml_load_string($this->s->Order_Globle_Search( "", "$fenid", "", "", "", "", "", "", "", "",     "", "",(int)$row -> UUpack_order , "", "", "", "", "", "", "1","0", 1, "0", "0","","0","0", "0",""));

                if(!$x -> Rec) continue;
                //判断传进来的fenid是不是直接下级
                if($x->Rec->UUaids!=0) {
                    $zhuid_s = $x->Rec->UUaids;

                    $zhuid_s = explode(',',$zhuid_s);
                    if($zhuid_s[1]!=$fenid) continue;
                }
                $a_x_id   =  (string)$x -> Rec -> UUsellid;
                $fen_x_id =  (string)$x -> Rec -> UUbuyid;
                //以下代码都是复制再下面的foreach里的 只是加了个判断 是否卖给指定的分销商
                // 转供应产品价格处理
                $row = $this->secondProOrderHandle($row);
                $row->UUlirun = $row->UUlirun ? $row->UUlirun  : $row->UUtotalmoney;
                // 获取这些订单销售的产品列表
                if(!in_array((string)$row->UUltitle,$products))
                    $products[(string)$row->UUlid]=(string)$row->UUltitle;

                // 根据分销商统计
                $arrId = ($by!='lid' && $by!='tid') ? (string)$row->UUbuyid:(string )$row->{$UUby};
                $result[$arrId]['ordernumInp'] .= (int)$row->UUordernum.',';
                // 根据景区或门票统计
                if($by == "lid") $result[$arrId]['title'] = (string )$row->UUltitle;
                if($by == "tid") $result[$arrId]['title'] = (string )$row->UUltitle.(string )$row->UUttitle;
                //已支付的订单才统计
                // if($row->UUpaystatus==1||($row->UUstatus==1)){
                if($a_x_id == $_SESSION['sid'] && $fen_x_id == $fenid){
                    if($row->UUpaystatus==1 && (string )$row->UUpmode != 4 ){
                        $result[$arrId]['order']++;
                        $result[$arrId]['tnum'] += $row->UUtnum;
                        $totalmoney = (float)$row->UUtnum*(float)$row->UUtprice;
                        $result[$arrId]['money'] += $totalmoney;
                        if((int)$row->UUpmode == 3)
                            //当支付方式是自供自销时 传到这个方法里判断下是否现场支付
                            $row->UUpmode = (int)$row->UUpaystatus == 0 ? 4:3;
                         if((int)$row->UUpmode == 0)// 余额
                             $result[$arrId]['pmode0'] += $totalmoney;
                         elseif((int)$row->UUpmode == 1)// 支付宝
                             $result[$arrId]['pmode1'] += $totalmoney;
                         elseif((int)$row->UUpmode == 2)// 授信支付
                             $result[$arrId]['pmode2'] += $totalmoney;
                         elseif((int)$row->UUpmode == 3)// 自销
                             $result[$arrId]['pmode3'] += $totalmoney;
                         elseif((int)$row->UUpmode == 4)// 现场支付
                             $result[$arrId]['pmode4'] += $totalmoney;
                         elseif((int)$row->UUpmode == 5)// 微信
                             $result[$arrId]['pmode5'] += $totalmoney;
                         elseif((int)$row->UUpmode == 7)// 银联
                             $result[$arrId]['pmode7'] += $totalmoney;
                         elseif((int)$row->UUpmode == 8)// 环迅
                             $result[$arrId]['pmode8'] += $totalmoney;
                    }
                }
            }
            foreach($result as $k => $v){
                $result[$k]['ordernumInp'] = substr($result[$k]['ordernumInp'],0,-1);
            }
            return $result;
        }
        if(1<=count($simplexml) &&  strlen($simplexml)>1){
            foreach ($simplexml->Rec as  $row) {
                //统计散客
                if($fid=='1sanke'){
                    if(!ismobile((string)$row->UUfromt))
                        continue;
                }
                if($ordernum == (int)$row->UUordernum)
                    continue;
                $ordernum = (int)$row->UUordernum;
                // 转供应产品价格处理
                $row = $this->secondProOrderHandle($row);
                // 获取这些订单销售的产品列表
                if(!in_array((string)$row->UUltitle,$products))
                    $products[(int)$row->UUlid]=(string)$row->UUltitle;

                // 根据分销商统计
                if($by!='lid' && $by!='tid'){
                    if($by=='aid')
                        $arrId = (int)$row->UUsellid;
                    else
                        $arrId = (int)$row->UUbuyid;
                }else
                    $arrId = (string )$row->{$UUby};
//                $arrId = ($by!='lid' && $by!='tid') ? (string)$row->UUbuyid:(string )$row->{$UUby};

                // 根据景区或门票统计
                if($by == "lid") $result[$arrId]['title'] = (string )$row->UUltitle;
                if($by == "tid") $result[$arrId]['title'] = (string )$row->UUltitle.(string )$row->UUttitle;
                //查询每级的支付方式
                $row = $this->pmode($row);

                //不是完成时间的话 取订单最开始的数量
                if($_GET['xtimes']!=3 && $_GET['order_type'] == 1){
                    $sql = "select pre_num from pft_order_num_modify where
                        orderid={$row->UUordernum} limit 1";
                    $GLOBALS['le']->query($sql);
                    $GLOBALS['le']->fetch_assoc();
                    if($tnum = $GLOBALS['le']->f('pre_num')){/*啥也不干*/ }
                    else
                     //订单的totalmoney会随着撤改变少 不能再从这里取最初始的值了
                       $tnum = (int)$row->UUtnum;
                }else if($_GET['order_type'] == 1){//时间类型是完成时间 并且选择了不看取消的订单时 只算验证时的门票数
                    //看下验证后没有修改数量 有的话取修改之前的数量就是验证时的数量 没有修改记录的话订单上记录的门票数量就是最终数量
                    $sql = "select pre_num from pft_order_num_modify where
                        orderid={$row->UUordernum} and rectime>'{$row->UUdtime}'
                        limit 1";
                    $GLOBALS['le']->query($sql);
                    $GLOBALS['le']->fetch_assoc();
                    if($tnum = $GLOBALS['le']->f('pre_num')){/*啥也不干*/ }
                    else $tnum = (int)$row->UUtnum;
                    //不含取消的报表 不统计取消的订单
                }else{
                    //if((int)$row->UUstatus==3) continue;
                    $tnum = (int)$row->UUtnum;
                }
                $result[$arrId]['order']++;
                $result[$arrId]['tnum'] += $tnum;
                $totalmoney = $tnum * (int)$row->UUtprice;
                $result[$arrId]['money'] += $totalmoney;
                $result[$arrId]['lirun'] += $row->UUlirun * $tnum;
                if($_SESSION['sid']==1)//管理员报表要区分是否测试景区
                    $result[$arrId]['lid'] = (int)$row->UUlid;
                if((int)$row->UUpmode == 3)
                    $row->UUpmode = (int)$row->UUpaystatus == 0 ? 4 : 3;
                if((int)$row->UUpmode == 0)// 余额
                    $result[$arrId]['pmode0'] += $totalmoney;
                elseif((int)$row->UUpmode == 1)// 支付宝
                    $result[$arrId]['pmode1'] += $totalmoney;
                elseif((int)$row->UUpmode == 2)// 授信支付
                    $result[$arrId]['pmode2'] += $totalmoney;
                elseif((int)$row->UUpmode == 3)// 自销
                    $result[$arrId]['pmode3'] += $totalmoney;
                elseif((int)$row->UUpmode == 4)// 现场支付
                    $result[$arrId]['pmode4'] += $totalmoney;
                elseif((int)$row->UUpmode == 5)// 微信
                    $result[$arrId]['pmode5'] += $totalmoney;
                elseif((int)$row->UUpmode == 7)// 银联
                    $result[$arrId]['pmode7'] += $totalmoney;
                elseif((int)$row->UUpmode == 8)// 环迅
                    $result[$arrId]['pmode8'] += $totalmoney;
            }
        }
        $this->products = $products; // 存储订单的产品，供使用
        return $result;
    }
    //admin报表 统计这个供应商经手的所有订单
    public function _orderSum_admin_only_aid($begintime, $endtime, $by = "lid",
                              $option = array(), $timeType=1, $fid=0)
    {
        if($_SESSION['sid']!=1) exit('thank you');
        $this->init();
        $this->handleRequest();
        $btime1 = $begintime;
        $etime1 = $endtime;
        $this->params['concat'] = 0;
        $this->params['sort'] ='';
        $this->params['orderby'] = '';
        $this->params['aid'] = '';
        if($fid>0) $this->params['mid'] = $fid;
        switch($timeType) {
            case 2:
                $this->params['btime2'] = $btime1;
                $this->params['etime2'] = $etime1;
                break;
            case 3:
                $this->params['btime3'] = $btime1;
                $this->params['etime3'] = $etime1;
                break;
            default:
                $this->params['btime1'] = $btime1;
                $this->params['etime1'] = $etime1;
                break;
        }
        foreach ($option as $key => $value) {
            $this->params[$key] = $value;
        }

        if(strpos('a'.$this->params['status'],'1') && !strpos('a'.$this->params['status'],'5')){
            $this->params['status']=$this->params['status'].'|5';
        }
        $simplexml = $this->ordersSimpleXml();

        $result = array();
        $products = array();
        if(1<=count($simplexml) &&  strlen($simplexml)>1){
            foreach ($simplexml->Rec as  $row) {
                // 获取这些订单销售的产品列表
                if(!in_array((string)$row->UUltitle,$products))
                    $products[(int)$row->UUlid]=(string)$row->UUltitle;

                // 根据分销商统计
                if($by=='mid'){
                   if((int)$row->UUmid==$fid){
                       $arrId = $fid;
                   }else{
                       $UUaids = (string)$row->UUaids.','.(string)$row->UUmid;
                       $UUaids = explode(',',$UUaids);
                       $arrId = $UUaids[array_search($fid,$UUaids)+1];
                   }
                }
                if($by=='aid'){
                    $arrId = (int)$row->UUsellid;
                }
                // 根据景区或门票统计
                if($by == "lid") $result[$arrId]['title'] = (string )$row->UUltitle;
                if($by == "tid") $result[$arrId]['title'] = (string )$row->UUltitle.(string )$row->UUttitle;
                $result[$arrId]['order']++;
                $tnum = (int)$row->UUtnum;
                $result[$arrId]['tnum'] += $tnum;
                $totalmoney = $tnum * (int)$row->UUtprice;
                $result[$arrId]['money'] += $totalmoney;
                $result[$arrId]['lid'] = (int)$row->UUlid;
                if((int)$row->UUpmode == 3)
                    $row->UUpmode = (int)$row->UUpaystatus == 0 ? 4 : 3;
                if((int)$row->UUpmode == 0)// 余额
                    $result[$arrId]['pmode0'] += $totalmoney;
                elseif((int)$row->UUpmode == 1)// 支付宝
                    $result[$arrId]['pmode1'] += $totalmoney;
                elseif((int)$row->UUpmode == 2)// 授信支付
                    $result[$arrId]['pmode2'] += $totalmoney;
                elseif((int)$row->UUpmode == 3)// 自销
                    $result[$arrId]['pmode3'] += $totalmoney;
                elseif((int)$row->UUpmode == 4)// 现场支付
                    $result[$arrId]['pmode4'] += $totalmoney;
                elseif((int)$row->UUpmode == 5)// 微信
                    $result[$arrId]['pmode5'] += $totalmoney;
                elseif((int)$row->UUpmode == 7)// 银联
                    $result[$arrId]['pmode7'] += $totalmoney;
                elseif((int)$row->UUpmode == 8)// 环迅
                    $result[$arrId]['pmode8'] += $totalmoney;
            }
        }
        $this->products = $products; // 存储订单的产品，供使用
        return $result;
    }
    /*
     *
     *  景区账号销售报表信息
     */
    public function _orderSumOnLand($begintime, $endtime, $by = "lid", $option = array(), $timeType=1, $fid=0,$aid=0)
    {
        $this->init();
        if($_SESSION['dtype'] == 3 && $_POST['salerid'])
            $this->params['sid'] = $_POST['salerid'];
        $btime1 = $begintime;
        $etime1 = $endtime;
        $this->params['concat'] = 0;
        $this->params['sort'] ='';
        $this->params['orderby'] = '';
//        if($fid>0) $this->params['mid'] = $fid;
//        if($aid>0) $this->params['aid'] = $aid;
        switch($timeType) {
            case 2:
                $this->params['btime2'] = $btime1;
                $this->params['etime2'] = $etime1;
                break;
            case 3:
                $this->params['btime3'] = $btime1;
                $this->params['etime3'] = $etime1;
                break;
            default:
                $this->params['btime1'] = $btime1;
                $this->params['etime1'] = $etime1;
                break;
        }
        foreach ($option as $key => $value) {
            $this->params[$key] = $value;
        }
        // 查询已使用时被终端修改也显示
        if(strpos('a'.$this->params['status'],'1') && !strpos('a'.$this->params['status'],'5')){
            $this->params['status']=$this->params['status'].'|5';
        }
        $simplexml = $this->ordersSimpleXml();

        $result = $price = $products = array();
        $ordernum='';
        if($simplexml->Rec[0]->UUordernum){
            foreach ($simplexml->Rec as $row) {
                if($ordernum == (int)$row->UUordernum)
                    continue;
                $ordernum = (int)$row->UUordernum;
                if(!$products[(int)$row->UUtid])
                    $products[(int)$row->UUtid]=(string)$row->UUltitle.(string)$row->UUttitle;
//
                    //过期产品 价格是-1
//                    $row->UUtprice = $this->s->get_Dynamic_Price_Merge((string)$row->UUpid,(string)$row->UUbegintime,1);
                    if((string)$row->UUaids_price!='0'){
                        $UUaids_price = explode(',',(string)$row->UUaids_price);
                        $row->UUtprice = $UUaids_price[0];
                    }
                // 按门票统计
                $result[(string)$row->UUtid]['title'] = (string)$row->UUltitle.(string)$row->UUttitle;

                ++$result[(int)$row->UUtid]['order'];
                $result[(int)$row->UUtid]['tnum'] += (int)$row->UUtnum;
                $totalmoney = (int)$row->UUtnum*(int)$row->UUtprice;
                $result[(int)$row->UUtid]['money'] += $totalmoney;
                if((int)$row->UUpmode == 3)
                    $row->UUpmode = (int)$row->UUpaystatus == 0 ? 4 : 3;
                if((int)$row->UUpmode == 0)// 余额
                    $result[(int)$row->UUtid]['pmode0'] += $totalmoney;
                elseif((int)$row->UUpmode == 1)// 支付宝
                    $result[(int)$row->UUtid]['pmode1'] += $totalmoney;
                elseif((int)$row->UUpmode == 2)// 授信支付
                    $result[(int)$row->UUtid]['pmode2'] += $totalmoney;
                elseif((int)$row->UUpmode == 3)// 自销
                    $result[(int)$row->UUtid]['pmode3'] += $totalmoney;
                elseif((int)$row->UUpmode == 4)// 现场支付
                    $result[(int)$row->UUtid]['pmode4'] += $totalmoney;
                elseif((int)$row->UUpmode == 5)// 微信
                    $result[(int)$row->UUtid]['pmode5'] += $totalmoney;
                elseif((int)$row->UUpmode == 7)// 银联
                    $result[(int)$row->UUtid]['pmode7'] += $totalmoney;
                elseif((int)$row->UUpmode == 8)// 环迅
                    $result[(int)$row->UUtid]['pmode8'] += $totalmoney;
            }
        }
        $this->products = $products;
        return $result;
    }
    /*
     public function ordersCount()
     {
         $params = $this->params;
         extract($params);
         return $this->s->Order_Globle_Search($sid, $mid, $lid, $tid, $ltitle, $ttitle, $btime1,
             $etime1, $btime2, $etime2, $btime3, $etime3, $ordernum, $oname, $otel, $status,
             $pays, $fromt, $orderby, $sort, $rstart, $n, 2, $stype, $payinfo, $pmode, $remotenum,
             $origin, $p_type, $order_confirm, $aid, $concat, $ifpack);

     }*/

    /**
     *订单查询Xml函数.
     *返回调用订单查询接口原始的数据
     *@see ProOrder::orderlist()
     *@see ProOrder::orderSum()
     *@return SimpleXml 订单数据
     */
    public function ordersSimpleXml()
    {
        $params = $this->params;
        extract($params);
        if($_GET['a']){
            echo "Order_Globle_Search($sid, $mid, $lid, $tid, $ltitle, $ttitle, $btime1,
                $etime1, $btime2, $etime2, $btime3, $etime3, $ordernum, $oname, $otel, $status,
                $pays, $fromt, $orderby, $sort, $rstart, $n, 0, $stype, $payinfo, $pmode, $remotenum,
                $origin, $p_type, $order_confirm, $aid, $concat, $ifpack, $ifTrans,$area,$contacttel)";
//            print_r($simplexml);
//            return;
        }
        $Hour = date('H',$_SERVER['REQUEST_TIME']);
        //9点后至7点可以查询
        if(!$sid &&!$aid && !$mid && !$lid && !$ltitle &&$n>10000 && $Hour>7 && $Hour<21) exit('请输入供应商或分销商或景区或在晚上9点后查询');
        $xml = $this->s->Order_Globle_Search($sid, $mid, $lid, $tid, $ltitle, $ttitle, $btime1,
            $etime1, $btime2, $etime2, $btime3, $etime3, $ordernum, $oname, $otel, $status,
            $pays, $fromt, $orderby, $sort, $rstart, $n, 0, $stype, $payinfo, $pmode, $remotenum,
            $origin, $p_type, $order_confirm, $aid, $concat, $ifpack, $ifTrans,$area,$contacttel);
        $simplexml =  simplexml_load_string($xml);
        return $simplexml;
    }


    public function totalOrders($t=1)
    {
        $params = $this->params;
        extract($params);
        if($_SESSION['dtype']==2 || $_SESSION['dtype']==3){
            $aid = $mid;
            $mid = '';
        }
        $ttotalOrders = $this->s->Order_Globle_Search($sid, $mid, $lid, $tid, $ltitle,
            $ttitle, $btime1, $etime1, $btime2, $etime2, $btime3, $etime3, $ordernum, $oname,
            $otel, $status, $pays, $fromt, $orderby, $sort, $rstart, $n, $t, $stype, $payinfo,
            $pmode, $remotenum, $origin, $p_type, $order_confirm, $aid, $concat, $ifpack, $ifTrans,$area,$contacttel);
        if($_GET['aa']){
            echo "Order_Globle_Search($sid, $mid, $lid, $tid, $ltitle,
            $ttitle, $btime1, $etime1, $btime2, $etime2, $btime3, $etime3, $ordernum, $oname,
            $otel, $status, $pays, $fromt, $orderby, $sort, $rstart, $n, $t, $stype, $payinfo,
            $pmode, $remotenum, $origin, $p_type, $order_confirm, $aid, $concat, $ifpack, $ifTrans,$area,$contacttel)";
            var_dump($ttotalOrders);
         }
        return $ttotalOrders;
    }

    public function totalOrders_lastLevel($t=9)
    {
        $params = $this->params;
//        print_r($params);
        extract($params);
       if($_GET['aaa']){
           echo "Order_Globle_Search($sid, $mid, $lid, $tid, $ltitle,
           $ttitle, $btime1, $etime1, $btime2, $etime2, $btime3, $etime3, $ordernum, $oname,
           $otel, $status, $pays, $fromt, $orderby, $sort, $rstart, $n, $t, $stype, $payinfo,
           $pmode, $remotenum, $origin, $p_type, $order_confirm, $aid, $concat, $ifpack, $ifTrans,$area,$contacttel)";
       }
        $mid = $aid = $ordernum = $ltitle = $area = '';
        $ttotalOrders = $this->s->Order_Globle_Search($sid, $mid, $lid, $tid, $ltitle,
            $ttitle, $btime1, $etime1, $btime2, $etime2, $btime3, $etime3, $ordernum, $oname,
            $otel, $status, $pays, $fromt, $orderby, $sort, $rstart, $n, $t, $stype, $payinfo,
            $pmode, $remotenum, $origin, $p_type, $order_confirm, $aid, $concat, $ifpack,
            $ifTrans,$area,$contacttel);
        return $ttotalOrders;
    }

    //处理每级分销的支付方式
    public function pmode($order){
        if(
            (string)$order->UUaids!='0' &&  //供销参与人数超过2个
            (int)$order->UUbuyid!=(int)$order->UUorigin_mid && //不是最后一级
            $_SESSION['sid']!=1  //不是管理员
        )
        {
            $aid_position = (string)$order->UUaids;
            $aid_position = explode(',',$aid_position);
            if($_SESSION['sid']==36624 && $aid_position[0]==$aid_position[1]) {//自己转分销给自己
                $aid_position = array_unique($aid_position);
                $aid_position = array_values($aid_position);
            }
            $aid_money = unserialize($order->UUaids_money);
            if($GLOBALS['v']['title'] == '已买到的产品' || $_SERVER['SCRIPT_URL']=='/buyOrderReport.html'){
                foreach($aid_money as $v){
                    if($v[0]==$_SESSION['sid']){
                        $order->UUpmode = $v[1]== 1 ?
                            '0'//余额
                            :'2'//授信
                        ;
                        break;
                    }
                }
            }
            else{
                //查找自己在aids中的位置 然后在$aid_money中找自己的下一级在哪里
                if($_SESSION['dtype']==2 || $_SESSION['dtype']==3)
                    $aid = $aid_position[0];
                else
                    $aid = $_SESSION['sid'];
                $position = array_search($aid,$aid_position);
                if($position != count($aid_position)-1){
                    foreach($aid_money as  $v){
                        if($v[0]==$aid_position[$position+1]){
                            $order->UUpmode = $v[1]== 1 ? '0' : '2';
                            break;
                        }
                    }
                }
            }
        }
        return $order;
    }

    //如果是统计撤改和取消的订单的话 传到这个方法里来统计
    public function cancel($simplexml,$by){
        $result = array();
        $UUby = "UU$by";
        if(count($simplexml) &&  strlen($simplexml)>1){
            foreach($simplexml->Rec as $v){
                $v = $this->secondProOrderHandle($v);
                $v = $this->pmode($v);

                // if($_GET['xtimes']==3){//时间类型是完成时间时 只统计验证后撤改的
                //     $sql = "select pre_num,rectime,done_num from pft_order_num_modify where
                // orderid={$v->UUordernum} and rectime>'{$v->UUdtime}'";
                //     $GLOBALS['le']->query($sql);
                //     while($row=$GLOBALS['le']->fetch_assoc()){
                //         $row['rectime'] = substr($row['rectime'],0,10);
                //         // 根据分销商统计
                //         $arrId = ($by!='lid' && $by!='tid') ? (string)$v->UUbuyid:(string )$v->{$UUby};
                //         // 根据景区或门票统计
                //         if($by == "lid") $result[$arrId.$row['rectime']]['title'] = (string )$v->UUltitle;
                //         if($by == "tid") $result[$arrId.$row['rectime']]['title'] = (string )$v->UUltitle.(string )$v->UUttitle;
                //         $tnum = $row['pre_num'] - $row['done_num'];
                //         $totalmoney = $tnum * $v->UUtprice;
                //         $result[$arrId.$row['rectime']]['tnum'] += $tnum;
                //         $result[$arrId.$row['rectime']]['money'] += $totalmoney;
                //         $result[$arrId.$row['rectime']]['time'] = $row['rectime'];

                //         if((int)$row->UUpmode == 3)
                //             $row->UUpmode = (int)$row->UUpaystatus == 0 ? 4 : 3;
                //         if((int)$row->UUpmode == 0)// 余额
                //             $result[$arrId]['pmode0'] += $totalmoney;
                //         elseif((int)$row->UUpmode == 2)// 授信支付
                //             $result[$arrId]['pmode2'] += $totalmoney;
                //         elseif((int)$row->UUpmode == 3)// 自销
                //             $result[$arrId]['pmode3'] += $totalmoney;
                //         elseif((int)$row->UUpmode == 4)// 现场支付
                //             $result[$arrId]['pmode4'] += $totalmoney;
                //         else{
                //             $online_pay = array(1,5,7,8);
                //             if(in_array((int)$row->UUpmode,$online_pay))// 支付宝
                //                 $result[$arrId]['pmode1'] += $totalmoney;
                //         }
                //     }
                //     continue;
                // }
                //******撤改的部分
                //2015-08-04 不知道什么时候开始 取消的订单也会在pft_order_num_modify里面记录数据了
                $sql = "select pre_num,rectime,done_num from pft_order_num_modify where
                orderid={$v->UUordernum}";
                if ($_GET['xtimes'] == 3) {
                    $sql .= ' and rectime > '.$v->UUdtime;
                }
                $GLOBALS['le']->query($sql);
                while($row=$GLOBALS['le']->fetch_assoc()){
                    $row['rectime'] = substr($row['rectime'],0,10);
                    // 根据分销商统计
                    $arrId = ($by!='lid' && $by!='tid') ? (string)$v->UUbuyid:(string )$v->{$UUby};
                    // 根据景区或门票统计
                    if($by == "lid") $result[$arrId.$row['rectime']]['title'] = (string )$v->UUltitle;
                    if($by == "tid") $result[$arrId.$row['rectime']]['title'] = (string )$v->UUltitle.(string )$v->UUttitle;
                    $tnum = $row['pre_num'] - $row['done_num'];
                    $totalmoney = $tnum * $v->UUtprice;
                    $result[$arrId.$row['rectime']]['tnum'] += $tnum;
                    $result[$arrId.$row['rectime']]['money'] += $totalmoney;
                    $result[$arrId.$row['rectime']]['time'] = $row['rectime'];
                    if((int)$row->UUpmode == 3)
                        $row->UUpmode = (int)$row->UUpaystatus == 0 ? 4 : 3;
                    if((int)$row->UUpmode == 0)// 余额
                        $result[$arrId.$row['rectime']]['pmode0'] += $totalmoney;
                    elseif((int)$row->UUpmode == 2)// 授信支付
                        $result[$arrId.$row['rectime']]['pmode2'] += $totalmoney;
                    elseif((int)$row->UUpmode == 3)// 自销
                        $result[$arrId.$row['rectime']]['pmode3'] += $totalmoney;
                    elseif((int)$row->UUpmode == 4)// 现场支付
                        $result[$arrId.$row['rectime']]['pmode4'] += $totalmoney;
                    else{
                        $online_pay = array(1,5,7,8);
                        if(in_array((int)$row->UUpmode,$online_pay))// 支付宝
                            $result[$arrId.$row['rectime']]['pmode1'] += $totalmoney;
                    }
                }
            }
        }
        return $result;
    }
}

/**
 *供应商销售订单.
 *会员身份为0供应商
 */
class SupSaleProOrder extends ProOrder
{
    public function __construct($did, $s)
    {
        parent::__construct($did, $s);
        parent::setInitParam("aid", $did);
        // 默认显示当天
        // if(!isset($_GET['begintime']))
        // parent::setInitParam('btime1',date('Y-m-d').' 00:00:00');
        // if(!isset($_GET['endtime']))
        // parent::setInitParam('etime1',date('Y-m-d H:i:s'));
    }
    public function weekSaleOrders()
    {
        $this->params['ifpack'] = 2;
        return $this->weekOrders();
    }
    public function monthSaleOrders()
    {
        $this->params['ifpack'] = 2;
        return $this->monthOrders();
    }
}
/**
 *供应商购买订单.
 *会员身份为0供应商
 */
class SupBuyProOrder extends ProOrder
{
    public function __construct($did, $s)
    {
        parent::__construct($did, $s);
        parent::setInitParam("mid", $did);
    }
    public function weekSaleOrders()
    {
        return $this->weekOrders();
    }
    public function monthSaleOrders()
    {

        return $this->monthOrders();
    }
}
/**
 *供应商转分销订单.
 */
class TransProOrder extends ProOrder
{
    public function __construct($did, $s)
    {
        parent::__construct($did, $s);
        parent::setInitParam("aid", $did);
        parent::setInitParam("ifTrans", 1);
    }
    public function weekSaleOrders()
    {
        return $this->weekOrders();
    }
    public function monthSaleOrders()
    {

        return $this->monthOrders();
    }
}
/**
 * 供应商转分销订单.
 *
 * 购买
 */
class TransProOrderBuy extends ProOrder
{
    public function __construct($did, $s)
    {
        parent::__construct($did, $s);
        parent::setInitParam("mid", $did);
        parent::setInitParam("ifTrans", 1);
    }
    public function weekSaleOrders()
    {
        return $this->weekOrders();
    }
    public function monthSaleOrders()
    {

        return $this->monthOrders();
    }
}
/**
 *分销商购买订单.
 *会员身份为1分销商
 */
class DisBuyProOrder extends ProOrder
{
    public function __construct($did, $s)
    {
        parent::__construct($did, $s);
        parent::setInitParam("mid", $did);

    }
    public function weekSaleOrders()
    {
        return $this->weekOrders();
    }
    public function monthSaleOrders()
    {

        return $this->monthOrders();
    }
}


/**
 *资源方销售订单.
 *会员身份为2供应商
 */
class ResourceSaleProOrder extends ProOrder
{
    public function __construct($did, $s, $salerid=null)
    {
        parent::__construct($did, $s);
        if($_SESSION['dtype'] == 3){
            $sql = "select preSalerID from pft_terminal_share where nowSalerID={$_SESSION['saccount']}";
            $GLOBALS['le']->query($sql);
            $salerid = '';
            while($row=$GLOBALS['le']->fetch_assoc()){
                $salerid .= $row['preSalerID'].',';
            }
            $salerid = rtrim($salerid,',');
        }
        parent::setInitParam("sid", $salerid);
    }
    public function weekSaleOrders()
    {
        $this->params['ifpack'] = 2;
        return $this->weekOrders();
    }
    public function monthSaleOrders()
    {
        $this->params['ifpack'] = 2;
        return $this->monthOrders();
    }
}


/**
 *普通用户购买订单.
 *会员身份为5普通用户
 */
class mobileBuyProOrder extends ProOrder
{
    public function __construct($did, $s)
    {
        parent::__construct($did, $s);
        parent::setInitParam("stype", 1);
    }
    public function weekSaleOrders()
    {
        return $this->weekOrders();
    }
    public function monthSaleOrders()
    {

        return $this->monthOrders();
    }
}


/**
 *集团销售订单.
 *会员身份为7集团账号
 */
class GroupSaleProOrder extends ProOrder
{
    public function __construct($did, $s)
    {
        parent::__construct($did, $s);
        $son_ids = array($did);
        $str = "select son_id from pft_member_relationship where parent_id=$did and son_id_type=3 and ship_type=1";
        $GLOBALS['le']->query($str);
        while ($row = $GLOBALS['le']->fetch_assoc()) {
            $son_ids[] = $row['son_id'];
        }
        parent::setInitParam("aid", implode("|", $son_ids));
    }
    public function weekSaleOrders()
    {
        return $this->weekOrders();
    }
    public function monthSaleOrders()
    {

        return $this->monthOrders();
    }
}

/**
 *管理员订单.
 *会员身份为9供应商
 */
class AdminProOrder extends ProOrder
{
    public function __construct($did, $s)
    {
        parent::__construct($did, $s);
        if (empty($_SERVER['QUERY_STRING'])) {
            parent::setInitParam("mid", 1);
            parent::setInitParam("aid", 1);
        }
    }
    public function monthSaleOrders()
    {
        $this->params['ifpack'] = 2;
        return $this->monthOrders();
    }
    public function weekSaleOrders()
    {
        $this->params['ifpack'] = 2;
        return $this->weekOrders();
    }
    public function daySaleOrders(){
        $this->params['ifpack'] = 2;
        return $this->dayOrders();
    }
}

/*
 * 合并后的终端类型的帐号 类型为3
 * */
/*
class TerminalProOrder extends ProOrder
{
    public function __construct($did, $s, $salerid=null)
    {
        parent::__construct($did, $s);
        $sql = "select preSalerID from pft_terminal_share where nowSalerID={$_SESSION['saccount']}";
        $GLOBALS['le']->query($sql);
        $salerid = '';
        while($row=$GLOBALS['le']->fetch_assoc()){
            $salerid .= $row['preSalerID'].',';
        }
        $salerid = rtrim($salerid,',');
        parent::setInitParam("sid", $salerid);
        //多个供应商发布同一个景区 只有salerid是一样的
        //查出来的订单只有第一级的
    }
    public function weekSaleOrders()
    {
        $this->params['ifpack'] = 2;
        return $this->weekOrders();
    }
    public function monthSaleOrders()
    {
        $this->params['ifpack'] = 2;
        return $this->monthOrders();
    }
}
*/
/**
 *已买到的订单对象函数.
 *由传入会员类型返回对应的订单对象，查询已买到的产品
 *@param int $did 会员ID
 *@param objcet $s 票付通内部接口对象
 *@param int $type 会员类型
 *@return object
 */
function buyProOrderObject($did, $s, $type)
{
    if (trim($type)=='TRANS') {
        //TODO::转分销订单
        return new TransProOrderBuy($did, $s);
    }
    elseif ($type == 0) {
        return new SupBuyProOrder($did, $s);
    } elseif ($type == 1) {
        return new DisBuyProOrder($did, $s);
    } elseif ($type == 5) {
        return new MobileBuyProOrder($did, $s);
    }elseif ($type == 9) {
        return new AdminProOrder($did, $s);
    }
}

/**
 *已卖出的订单对象函数.
 *由传入会员类型返回对应的订单对象，查询已卖出的产品
 *@param int $did 会员ID
 *@param objcet $s 票付通内部接口对象
 *@param int $type 会员类型
 *@return object
 */
function saleProOrderObject($did, $s, $type,$salerid=null)
{
    if (trim($type)=='TRANS') {
        //TODO::转分销订单
        return new TransProOrder($did, $s);
    }
    elseif ($type == 0 || $type==1) {
        return new SupSaleProOrder($did, $s);
//    } elseif ($type == 1) {
//        return new DisBuyProOrder($did, $s);
    } elseif ($type == 2 || $type==3) {
        return new ResourceSaleProOrder($did, $s, $salerid);
    } elseif ($type == 7) {
        return new GroupSaleProOrder($did, $s);
    } elseif ($type == 9) {
        return new AdminProOrder($did, $s);
    }
//    elseif ($type == 3) {
//        return new TerminalProOrder($did, $s);
//    }
}
?>